const systemHelper = require('../../common/system-helper');
const sspUserService = require('../../services/ssp-user-service');
const messages = require('../../common/messages');

Page({
  data: {
    userPrompt: '点击登录按钮，开始登录。',
    jumpCode: '',
    showLogin: false,
  },
  doLogin: function () {
    systemHelper
      .getUserProfile()
      .then((userInfo) =>
        systemHelper
          .login()
          .then((res) => sspUserService.login(res.code, userInfo.nickName, userInfo.avatarUrl, this.data.jumpCode)),
      )
      .then((res) => {
        if (res.statusCode !== 200) {
          throw '登录失败';
        }
        // 登录成功，保存token和用户信息
        const { token, userInfo, expireTime } = res.data;
        wx.setStorageSync('token', token);
        wx.setStorageSync('userInfo', userInfo);
        wx.setStorageSync('expireTime', expireTime);

        if (this.globalData == null) {
          this.globalData = {};
        }
        this.globalData.userInfo = userInfo;
        this.globalData.token = token;
        this.setData({ userPrompt: '登录成功，请手动切回浏览器。', showLogin: false });
        messages.showMessage('登录成功');
      })
      .catch(messages.showError);
  },

  onLoad(options) {
    if (options.jumpCode) {
      this.setData({
        jumpCode: options.jumpCode,
        showLogin: true,
      });
    }
  },

  onReady() {},

  onShow() {},

  onHide() {},

  onUnload() {},

  onPullDownRefresh() {},

  onReachBottom() {},

  onShareAppMessage() {},
});
